
package com.kamikaze.lamg;

import com.waps.AppConnect;
import com.waps.UpdatePointsNotifier;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class MovieDetailActivity extends Activity {

    private TextView tvMovieNum;

    private MovieDBHelper dbHelper;

    private ViewPager pager;

    private int totalMovieNum;

    private TextView tvNowpoint;

    private Button btnPrev;

    private Button btnNext;

    private ProgressDialog progressDialog;

    private static final int MSG_GET_POINT_RETURN = 0;

    private static final int MSG_UPDATE_CODE = 1;

    protected static final int MSG_NOT_ENOUGH = 2;

    protected static final int MSG_GET_POINT = 3;

    private ConnectivityManager connectivityManager;

    private int nowPoint = -1;

    private AppConnect appConnect;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        connectivityManager = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
        setContentView(R.layout.detail_main);
        pager = (ViewPager) findViewById(R.id.pager);
        dbHelper = new MovieDBHelper(this);
        btnPrev = (Button) findViewById(R.id.btnPrev);

        btnNext = (Button) findViewById(R.id.btnNext);
        tvMovieNum = (TextView) findViewById(R.id.movieNum);
        totalMovieNum = dbHelper.getMovieCount();
        tvNowpoint = (TextView) findViewById(R.id.nowpoint);
        PagerAdapter adapter = new MoviePagerAdapter(dbHelper.getMovieInfos(), this);
        pager.setAdapter(adapter);
        int movieId = getIntent().getIntExtra("movieId", -1);
        int currentPosition = 0;
        if (movieId != -1) {
            currentPosition = dbHelper.getMoviePosition(movieId);
        }
        appConnect = AppConnect.getInstance(this);
        getPoint();
        pager.setCurrentItem(currentPosition);
        tvMovieNum.setText((currentPosition + 1) + "/" + totalMovieNum);
        pager.setOnPageChangeListener(changeListener);
        setNextPrevVisibility(0);
        findViewById(R.id.btnHome).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // Intent intent = new Intent(MovieDetailActivity.this,
                // MovieHomeActivity.class);
                // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                // startActivity(intent);
                finish();
            }
        });

        findViewById(R.id.btnShowOffers).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                AppConnect.getInstance(MovieDetailActivity.this).showOffers(
                        MovieDetailActivity.this);
            }
        });

    }

    private void getPoint() {
        appConnect.getPoints(new UpdatePointsNotifier() {

            @Override
            public void getUpdatePointsFailed(String arg0) {
                // Toast.makeText(MovieDetailActivity.this, arg0,
                // Toast.LENGTH_SHORT).show();
            }

            @Override
            public void getUpdatePoints(String arg0, int arg1) {
                nowPoint = arg1;
                Message msg = new Message();
                msg.what = MSG_GET_POINT_RETURN;
                msg.arg1 = arg1;
                handler.sendMessage(msg);
            }
        });
    }

    private void setNextPrevVisibility(int position) {
        if (position <= 0) {
            btnPrev.setVisibility(View.INVISIBLE);
        } else {
            btnPrev.setVisibility(View.VISIBLE);
        }
        if (position >= totalMovieNum - 1) {
            btnNext.setVisibility(View.INVISIBLE);
        } else {
            btnNext.setVisibility(View.VISIBLE);
        }

    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_GET_POINT_RETURN:
                    int point = msg.arg1;
                    tvNowpoint.setText("" + point);
                    break;
                case MSG_GET_POINT:
                    getPoint();
                    break;
                case MSG_UPDATE_CODE:
                    MoviePagerAdapter.CodeViewHold codeViewHold = (MoviePagerAdapter.CodeViewHold) msg.obj;
                    codeViewHold.btnGetCode.setVisibility(View.GONE);
                    codeViewHold.tvCode.setVisibility(View.VISIBLE);
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                        progressDialog = null;
                    }
                    handler.sendEmptyMessageDelayed(MSG_GET_POINT, 1000);
                    setResult(RESULT_OK, new Intent().putExtra("id", codeViewHold.movieId));
                    break;
                case MSG_NOT_ENOUGH:
                    new AlertDialog.Builder(MovieDetailActivity.this)
                            .setTitle(R.string.prompt)
                            .setMessage(R.string.prompt_point_not_enough)
                            .setPositiveButton(R.string.get_point,
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            AppConnect.getInstance(MovieDetailActivity.this)
                                                    .showOffers(MovieDetailActivity.this);
                                            dialog.dismiss();
                                        }
                                    })
                            .setNegativeButton(R.string.cancel,
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    }).show();
                    break;
            }

            super.handleMessage(msg);
        }

    };

    OnPageChangeListener changeListener = new OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            tvMovieNum.setText((position + 1) + "/" + totalMovieNum);
            setNextPrevVisibility(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    };

    @Override
    protected void onDestroy() {
        dbHelper.closeDatabase();
        super.onDestroy();
    }

    public class MoviePagerAdapter extends PagerAdapter {

        ArrayList<MovieInfo> mMovies;

        Context mContext;

        private TextView tvTitle;

        private TextView tvActress;

        private TextView tvParameter;

        private TextView tvIntroduction;

        private Button btnDetailShow;

        private Button btnDetailHidden;

        private Button btnBuyMovie;

        private TextView tvCode;

        private ImageView ivFrontcover;

        LayoutInflater inflater;

        FrameLayout layoutInfo;

        private class ViewHold {
            Button btnDetailShow;

            Button btnDetailHidden;

            TextView tvIntroduction;

        }

        private class CodeViewHold {
            int movieId;

            TextView tvCode;

            Button btnGetCode;
        }

        MoviePagerAdapter(ArrayList<MovieInfo> movies, Context context) {
            mMovies = movies;
            mContext = context;
            inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return mMovies.size();
        }

        /**
         * 从指定的position创建page
         * 
         * @param container ViewPager容器
         * @param position The page position to be instantiated.
         * @return 返回指定position的page，这里不需要是一个view，也可以是其他的视图容器.
         */
        @Override
        public Object instantiateItem(View collection, int position) {

            View view = inflater.inflate(R.layout.detail_item, null);
            tvTitle = (TextView) view.findViewById(R.id.title);
            tvActress = (TextView) view.findViewById(R.id.actress);
            tvParameter = (TextView) view.findViewById(R.id.parameter);
            tvIntroduction = (TextView) view.findViewById(R.id.introduction);
            ivFrontcover = (ImageView) view.findViewById(R.id.frontcover);
            btnDetailShow = (Button) view.findViewById(R.id.btnDetailShow);
            btnDetailHidden = (Button) view.findViewById(R.id.btnDetailHidden);
            tvCode = (TextView) view.findViewById(R.id.code);

            ViewHold vh = new ViewHold();
            vh.btnDetailHidden = btnDetailHidden;
            vh.btnDetailShow = btnDetailShow;
            vh.tvIntroduction = tvIntroduction;
            vh.btnDetailHidden.setTag(vh);
            vh.btnDetailShow.setTag(vh);
            btnBuyMovie = ((Button) view.findViewById(R.id.btnDownload));
            layoutInfo = (FrameLayout) view.findViewById(R.id.layoutInfo);
            layoutInfo.setTag(vh);
            setInfoView(mMovies.get(position));
            ((ViewPager) collection).addView(view);
            return view;
        }

        private void setInfoView(MovieInfo movieInfo) {
            tvTitle.setText(movieInfo.title);
            tvActress.setText(getString(R.string.actress, movieInfo.actress));
            tvParameter.setText(getString(R.string.parameter, movieInfo.duration,
                    movieInfo.filesize));
            tvIntroduction.setText(movieInfo.introduction);
            ivFrontcover.setImageBitmap(BitmapFactory.decodeByteArray(movieInfo.frontCover, 0,
                    movieInfo.frontCover.length));
            tvCode.setText(movieInfo.code);
            CodeViewHold codeViewHold = new CodeViewHold();
            codeViewHold.btnGetCode = btnBuyMovie;
            codeViewHold.tvCode = tvCode;
            codeViewHold.movieId = movieInfo.id;

            if (movieInfo.purchased) {
                tvCode.setVisibility(View.VISIBLE);
                btnBuyMovie.setVisibility(View.GONE);
            } else {
                tvCode.setVisibility(View.GONE);
                btnBuyMovie.setVisibility(View.VISIBLE);
            }
            ivFrontcover.setTag(movieInfo);

            ivFrontcover.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent i = new Intent(mContext, MovieImageActivity.class);
                    MovieInfo movieInfo = (MovieInfo) v.getTag();
                    i.putExtra("movieInfo", movieInfo);
                    mContext.startActivity(i);
                }
            });
            layoutInfo.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    ViewHold vh = (ViewHold) v.getTag();
                    int visibility = vh.btnDetailShow.getVisibility();
                    switch (visibility) {
                        case View.VISIBLE:
                            vh.tvIntroduction.setVisibility(View.VISIBLE);
                            vh.btnDetailHidden.setVisibility(View.VISIBLE);
                            vh.btnDetailShow.setVisibility(View.GONE);
                            break;
                        case View.GONE:
                            vh.tvIntroduction.setVisibility(View.GONE);
                            vh.btnDetailHidden.setVisibility(View.GONE);
                            vh.btnDetailShow.setVisibility(View.VISIBLE);
                            break;
                    }
                }

            });
            btnDetailShow.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    ViewHold vh = (ViewHold) v.getTag();
                    vh.tvIntroduction.setVisibility(View.VISIBLE);
                    vh.btnDetailHidden.setVisibility(View.VISIBLE);
                    vh.btnDetailShow.setVisibility(View.GONE);
                }
            });

            btnDetailHidden.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    ViewHold vh = (ViewHold) v.getTag();
                    vh.tvIntroduction.setVisibility(View.GONE);
                    vh.btnDetailHidden.setVisibility(View.GONE);
                    vh.btnDetailShow.setVisibility(View.VISIBLE);
                }
            });
            btnBuyMovie.setTag(codeViewHold);
            btnBuyMovie.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (!Utils.getNetState(connectivityManager)) {
                        Toast.makeText(mContext, R.string.net_unconnect, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    purchase((CodeViewHold) v.getTag());
                }
            });
        }

        /**
         * <span style="font-family:'Droid Sans';">从指定的position销毁page</span>
         * <span style="font-family:'Droid Sans';">参数同上</span>
         */
        @Override
        public void destroyItem(View collection, int position, Object view) {
            ((ViewPager) collection).removeView((View) view);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == (object);
        }
    }

    private void purchase(MoviePagerAdapter.CodeViewHold codeViewHold) {
        final MoviePagerAdapter.CodeViewHold cvh = codeViewHold;
        int price_tmp = 20;
        String price_str = appConnect.getConfig("price");
        if (price_str != null) {
            try {
                price_tmp = Integer.parseInt(price_str);
            } catch (NumberFormatException e) {
                price_tmp = 20;
            }
        }

        final int price = price_tmp;
        if (nowPoint != -1 && nowPoint < price) {
            handler.sendEmptyMessage(MSG_NOT_ENOUGH);
            return;
        }

        new AlertDialog.Builder(this).setMessage(getString(R.string.prompt_buy, price))
                .setTitle(R.string.prompt)
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        AppConnect.getInstance(MovieDetailActivity.this).spendPoints(price,
                                new MyUpdatePointsNotifier(MovieDetailActivity.this, cvh));
                        progressDialog = new ProgressDialog(MovieDetailActivity.this);
                        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                        progressDialog.setMessage(getText(R.string.loading));
                        progressDialog.setIndeterminate(true);
                        progressDialog.setCanceledOnTouchOutside(false);
                        progressDialog.show();
                    }
                }).show();

    }

    class MyUpdatePointsNotifier implements UpdatePointsNotifier {
        Context mContext;

        MoviePagerAdapter.CodeViewHold codeViewHold;

        int movieId;

        MyUpdatePointsNotifier(Context context, MoviePagerAdapter.CodeViewHold codeViewHold) {
            mContext = context;
            this.codeViewHold = codeViewHold;
            movieId = codeViewHold.movieId;
        }

        @Override
        public void getUpdatePoints(String currencyName, int totalPoint) {
            dbHelper.updateMovieShow(movieId, true);
            Message msg = new Message();
            msg.what = MSG_UPDATE_CODE;
            msg.obj = this.codeViewHold;
            handler.sendMessage(msg);
        }

        @Override
        public void getUpdatePointsFailed(String error) {
            // handler.sendEmptyMessage(MSG_NOT_ENOUGH);
        }

    }

}
